package com.jingyanzi.member.service.impl;

import java.util.Calendar;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jingyanzi.member.dao.MIntegralLogMapper;
import com.jingyanzi.member.dao.MIntegralMapper;
import com.jingyanzi.member.domain.IntegralDO;
import com.jingyanzi.member.domain.IntegralLogDO;
import com.jingyanzi.member.domain.result.ResultDO;
import com.jingyanzi.member.domain.result.ResultSupport;
import com.jingyanzi.member.entity.MIntegral;
import com.jingyanzi.member.entity.MIntegralLog;
import com.jingyanzi.member.entity.MIntegralLogExample;
import com.jingyanzi.member.entity.MIntegralLogExample.Criteria;
import com.jingyanzi.member.query.IntegRalLogQueryDO;
import com.jingyanzi.member.service.ICustomerSolrService;
import com.jingyanzi.member.service.IIntegralLogService;
import com.jingyanzi.member.util.BeanUtilsExtends;
import com.jingyanzi.member.util.MemberConstant;

@Service("integralLogService")
public class IntegralLogServiceImpl extends BaseServiceImpl implements IIntegralLogService {

	private static Logger logger = Logger.getLogger(IntegralLogServiceImpl.class);

	@Autowired
	private MIntegralLogMapper integralLogMapper;

	@Autowired
	private MIntegralMapper integralMapper;
	
	/*@Autowired
	private ICustomerSolrService solrService;*/

	public ResultDO addLog(IntegralDO domain) {
		MIntegral entity = new MIntegral();
		MIntegralLog integralLog = new MIntegralLog();

		ResultSupport result = BeanUtilsExtends.copy(entity, domain);
		if (!result.isSuccess()) {
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("积分数据处理失败");
			result.setSuccess(false);
			logger.error("积分记录DO对象转换失败");
			return result;
		}

		// 1. 组织会员积分数据
		MIntegral miIntegral = null;
		try {
			// 查询会员积分信息
			miIntegral = integralMapper.selectByPrimaryKey(domain.getMemberId());
			// 会员不存在或会员已失效
			if (null == miIntegral || miIntegral.getIsDelete() == MemberConstant.DB_ISDEL_YES) {
				result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
				result.setErrorMsg("未查到该会员信息");
				result.setSuccess(false);
				logger.error("会员信息不存在");
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG + "获取会员积分信息失败");
			result.setSuccess(false);
			result.setErrorMsg("会员积分信息获取失败");
			result.setSuccess(false);
			logger.error("会员积分信息获取失败");
			return result;
		}

		// 操作类型 1：添加 2：扣除
		if (domain.getOpType() == MemberConstant.MEMBER_INTEGRAL_ADD) {
			// 新增积分
			integralLog.setPayType("增加积分");
			entity.setTotleIntegral(miIntegral.getTotleIntegral() + domain.getIntegral());
			entity.setExp(miIntegral.getExp() + domain.getIntegral()); // 写入累计经验
			entity.setChangeNumber(domain.getIntegral()); // 最近新增积分
			entity.setChangeDate(Calendar.getInstance().getTime());
			logger.info("会员新增积分， 会员id:" + domain.getMemberId() + ", 新增积分：" + domain.getIntegral() + "，事由："
					+ domain.getOpInfo() + ", 最新积分余额：" + entity.getTotleIntegral());
		} else {
			// 判断积分余额是否足够
			if (miIntegral.getTotleIntegral() < domain.getIntegral()) {
				result.setErrorCode(ResultDO.MEMBER_EXCHANGEGIFT_ERROR);
				result.setErrorMsg("账户积分不足");
				result.setSuccess(false);
				logger.error("账户积分不足, 账户积分：" + miIntegral.getTotleIntegral() + ", 积分消费：" + domain.getIntegral());
				return result;
			}
			integralLog.setPayType("扣除积分");
			entity.setTotleIntegral(miIntegral.getTotleIntegral() - domain.getIntegral());
			entity.setUseIntegral(domain.getIntegral()); // 最近消费积分
			entity.setUseDate(Calendar.getInstance().getTime());
			logger.info("会员积分扣除， 会员id:" + domain.getMemberId() + ", 扣除积分：" + domain.getIntegral() + "，事由："
					+ domain.getOpInfo() + ", 最新积分余额：" + entity.getTotleIntegral());
		}

		// 2. 写入积分log记录表
		integralLog.setMemberId(domain.getMemberId());
		integralLog.setIntegralId(domain.getMemberId());
		integralLog.setChangeIntegral(domain.getIntegral());
		integralLog.setBalanceIntegral(entity.getTotleIntegral());
		// 积分事由
		integralLog.setDesp(domain.getOpInfo());
		// 业务单号、订单编号
		integralLog.setTradeNo(domain.getTradeNo());
		integralLog.setOrderNo(domain.getOrderNo());
		integralLog.setAuthor(entity.getModifi());
		integralLog.setCreatetime(Calendar.getInstance().getTime());

		int r = -1;
		try {
			r = integralLogMapper.insert(integralLog);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.QUERY_VALUE_SET_ERROR);
			result.setErrorMsg("会员积分记录保存失败");
			result.setSuccess(false);
			logger.error("会员积分log记录保存异常");
			return result;
		}
		if (r < 1) {
			result.setErrorCode(ResultDO.QUERY_VALUE_SET_ERROR);
			result.setErrorMsg("会员积分记录保存失败");
			result.setSuccess(false);
			logger.error("会员积分log记录保存失败");
			return result;
		}

		// 3. 更新积分信息表：积分余额等信息
		entity.setId(domain.getMemberId());
		entity.setModifitime(Calendar.getInstance().getTime());
		try {
			r = integralMapper.updateByPrimaryKeySelective(entity);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("会员积分信息修改失败");
			result.setSuccess(false);
			logger.error("会员积分信息修改异常");
			return result;
		}
		if (r < 1) {
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("会员积分信息修改失败");
			result.setSuccess(false);
			logger.error("会员积分信息修改失败");
			return result;
		}

		// 更新solr
		//solrService.addRecord(domain.getMemberId());

		result.setModel(ResultDO.FIRST_MODEL_KEY, entity.getId());
		return result;
	}

	public ResultDO get(Integer id) {

		ResultSupport result = new ResultSupport();

		if (isNumberInValid(id)) {
			result.setErrorCode(ResultDO.PARAM_ERROR);
			result.setErrorMsg("参数错误");
			result.setSuccess(false);
			logger.error("参数错误，id无效");
			return result;
		}

		MIntegralLog entity = null;
		try {
			entity = integralLogMapper.selectByPrimaryKey(id);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.QUERY_VALUE_SET_ERROR);
			result.setErrorMsg("积分记录信息获取失败");
			result.setSuccess(false);
			logger.error("积分记录信息获取失败, id:" + id);
			return result;
		}

		result.setModel(ResultSupport.FIRST_MODEL_KEY, getIntegralLogDO(entity));
		return result;
	}

	@Override
	public ResultDO query(IntegRalLogQueryDO query) {
		ResultSupport result = new ResultSupport();

		List<MIntegralLog> list = null;

		MIntegralLogExample example = new MIntegralLogExample();

		Criteria createCriteria = example.createCriteria();

		if (!isNumberInValid(query.getMemberId())) {
			createCriteria.andMemberIdEqualTo(query.getMemberId());
		}

		if (query.isPage()) {
			example.setLimitByPage(query.getStart() + "," + query.getPageRows());
			long count = integralLogMapper.countByExample(example);
			result.setModel(ResultSupport.SECOND_MODEL_KEY, count);
		}

		try {
			list = integralLogMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.QUERY_VALUE_SET_ERROR);
			result.setErrorMsg("会员积分列表查询失败");
			result.setSuccess(false);
			logger.error("会员积分列表查询失败, id=" + query.getMemberId());
			return result;
		}

		List<IntegralLogDO> doList = getIntegralLogDOList(list);
		result.setModel(ResultSupport.FIRST_MODEL_KEY, doList);

		return result;
	}
}
